// miniprogram/pages/manager/editAbility/editAbility.js

var util = require('../../../../utils/utils.js');
const db = wx.cloud.database()
const _ = db.command
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */

  data: {
    HistoryRemark:{},
    MyhistoryLink:'',
    MyhistoryTopic:'',
    MyhistoryRemark:'',
    History:[],
    Myhistory :{
      Topic:'',
      AbilityType : '',
      remark:'',
      link :'',
      Images:[],
      Time:'',
    },
    // 上传的案例图片集合
    cloudImages: [],
    uploadImages: [],
    // 设置上传案例图片的最大数目
    maxImages: 9,
    // 案例图片数目是否达到了最大数目

    Activity: {
      name: "",
      rule: "",
      prize: "",
      InformUrl: "",
      type: "",

      ApplyTimeStart: '2020-08-03',
      ApplyTimeEnd: '2020-08-03',
      ActivityTimeEnd: '2020-08-03',
      ActivityTimeStart: '2020-08-03',
      confirmxueyue: [],
      confirmnianji: [],
      uploadImages: [],
    },

    isMaxImagesNum: false,

    val: [// 数据列表
      ['体育活动', '艺术活动', '学术活动', '其他活动'],

    ],
    isFocus: false,
    select: false,
    select2: false,
    type: '体育活动',
    Object: '体育活动',
    
    hidden: true,

    show: false,
    animationData: '',
    parameter: [{ id: 1, name: '银色' }, { id: 2, name: '白色' }, { id: 3, name: '黑色' }],
    confirmxueyue: [],
    confirmnianji: [],
    haveConfirm: false,
    
    AbilityType: '',

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.data.parameter[0].checked = true;
    this.setData({
      parameter: this.data.parameter,
    })//默认parameter数组的第一个对象是选中的

    console.log(this.data.Activity.ApplyTimeEnd)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    console.log(this.data.HistoryRemark)
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    console.log(this.data.HistoryRemark)
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  bindShowMsg() {
    this.setData({
      select: !this.data.select
    })
  },
  bindShowMsg2() {
    this.setData({
      select2: !this.data.select2
    })
  },
  mySelect(e) {
    var name = e.currentTarget.dataset.name;
    this.setData({
      type: name,
      select: false
    })
  },
  mySelect2(e) {
    var name = e.currentTarget.dataset.name;
    this.setData({
      Object: name,
      select2: false
    })
  },
  bindChange: function (e) {
    const val = e.detail.value
    this.setData({
      year: this.data.years[val[0]],
      month: this.data.months[val[1]],
      day: this.data.days[val[2]],
      hour: this.data.hours[val[3]],
      minute: this.data.minutes[val[4]],
    })
    var totalDay = mGetDate(this.data.year, this.data.month);
    var changeDate = [];
    for (let i = 1; i <= totalDay; i++) {
      var k = i;
      if (0 <= i && i < 10) {
        k = "0" + i
      }
      changeDate.push(k)
    }
    this.setData({
      days: changeDate
    })
  },
  handleFocus() {
    this.setData({
      hidden: false
    })
  },
  endFocus() {
    this.setData({
      hidden: true
    })
  },
  blockTime() {
    this.setData({
      hidden: false
    })
  },
  datePickerBindchange1: function (e) {
    this.setData({
      ['Activity.ActivityTimeStart']: e.detail.value
    })
  },

  datePickerBindchange2: function (e) {
    this.setData({
      ['Activity.ActivityTimeEnd']: e.detail.value
    })
  },
  datePickerBindchange3: function (e) {
    this.setData({
      ['Activity.ApplyTimeStart']: e.detail.value
    })
  },

  datePickerBindchange4: function (e) {
    this.setData({
      ['Activity.ApplyTimeEnd']: e.detail.value
    })
  },
  filter: function (e) { //点击筛选事件
    var animation = wx.createAnimation({//创建动画
      duration: 1000,
      timingFunction: 'ease',
      width: 300,
      height: 800,
      top: 0,
      bottom: 0,
      right: 0,
      backgroundColor: '#fff',
      opcity: 0.5
    })

    this.animation = animation

    animation.translateX(-100 + 'vh').step() //动画效果向右滑动100vh

    this.setData({
      animationData: animation.export(),
      show: true
    })
  },
  // 参数点击响应事件
  parameterTap: function (e) {//e是获取e.currentTarget.dataset.id所以是必备的，跟前端的data-id获取的方式差不多
    var that = this
    var this_checked = e.currentTarget.dataset.id
    var parameterList = this.data.parameter//获取Json数组
    for (var i = 0; i < parameterList.length; i++) {
      if (parameterList[i].id == this_checked) {
        parameterList[i].checked = true;//当前点击的位置为true即选中
      }
      else {
        parameterList[i].checked = false;//其他的位置为false
      }
    }
    that.setData({
      parameter: parameterList
    })
  },

  getDemo2: function (e) {

    var that = this

    var index = e.currentTarget.dataset.index;//每一个button的索引

    var item = that.data.gd1List2[index];//每一个索引对应的内容

    item.isChecked2 = !item.isChecked2;//选中，未选中 两种状态切换

    that.setData({//更新到data

      gd1List2: that.data.gd1List2,

    });

  },
  getDemo3: function (e) {

    var that = this

    var index = e.currentTarget.dataset.index;//每一个button的索引

    var item = that.data.gd1List3[index];//每一个索引对应的内容

    item.isChecked2 = !item.isChecked2;//选中，未选中 两种状态切换

    that.setData({//更新到data

      gd1List3: that.data.gd1List3,

    });

  },
  confirmSelect() {
    var that = this
    var array3 = that.data.gd1List3
    var array = that.data.gd1List2
    var array2 = []
    var array4 = []
    for (var i = 0; i < array.length; i++) {
      if (array[0].isChecked2 == true) {
        array2.push(array[i]);
        break;
      }

      if (array[i].isChecked2 == true) {

        array2.push(array[i]);
      }
    }
    for (var i = 0; i < array3.length; i++) {
      if (array3[0].isChecked2 == true) {
        array4.push(array3[i]);
        break;
      }

      if (array3[i].isChecked2 == true) {

        array4.push(array3[i]);
      }
    }
    // var that = this

    that.setData({
      show: false,
      // gd1List2: that.data.gd1List2,
      // gd1List3: that.data.gd1List3,
      confirmnianji: array4,
      confirmxueyue: array2,
      haveConfirm: true
    });

  },
  reverseSelect() {
    var that = this
    var array1 = that.data.gd1List2
    var array2 = that.data.gd1List3
    for (var i = 0; i < array1.length; i++) {
      if (array1[i].isChecked2 == true) {
        array1[i].isChecked2 = false
      }
    }
    for (var i = 0; i < array2.length; i++) {
      if (array2[i].isChecked2 == true) {
        array2[i].isChecked2 = false
      }
    }
    that.setData({
      gd1List2: array1,
      gd1List3: array2
    })
  },

  submit: function () {

   // var activity = db.collection('user')

    // if (this.data.type == "体育活动") {
    //   console.log("tiyu")
    //   activity = db.collection('SportActivity')

    // }
    // else if (this.data.type == "学术活动") {
    //   activity = db.collection('AcademicActivity')
    // }
    // else if (this.data.type == "艺术活动") {
    //   activity = db.collection('ArtActivity')
    // }
    // else {
    //   activity = db.collection('AnotherAcitivity')
    // }

    // this.data.Activity.type = this.data.type
    // this.data.Activity.confirmnianji = this.data.confirmnianji
    // this.data.Activity.confirmxueyue = this.data.confirmxueyue
    this.data.Myhistory.Images = this.data.cloudImages
    this.data.Myhistory.AbilityType = this.data.AbilityType
    this.data.Myhistory.remark = this.data.MyhistoryRemark
    this.data.Myhistory.Topic = this.data.MyhistoryTopic
    this.data.Myhistory.link = this.data.MyhistoryLink
    this.data.Myhistory.Time = util.formatTime(new Date());
    console.log(this.data.Myhistory)
    this.data.History.push(this.data.Myhistory)
    console.log(this.data.History)

    const that =this
    db.collection('user').where({
      _openid: 'app.globalData.openid' // 填入当前用户 openid
    }).update({
      data:{
        ['publish.History']:_.push(that.data.Myhistory)
      },
      success:function(res){
        wx.navigateTo({
          url: '/pages/manager/success/success',
        })
      }
    })
     
    
  },
  
  addurl: function (e) {
    this.setData({
      MyhistoryLink: e.detail.value
    })
  },

  addname: function (e) {
    this.setData({
      MyhistoryTopic: e.detail.value
    })

  },
  finishHandler(e) {

    console.log(e.detail)// 选择的结果 如：["妖刀姬", "犬神"]
    this.setData({
      AbilityType: e.detail.join('')
    })
  },
  // 选择图片
  chooseImageTap: function () {
    let _this = this;
    wx.showActionSheet({
      itemList: ['从相册中选择', '拍照'],
      itemColor: "#f7982a",
      success: function (res) {
        if (!res.cancel) {
          if (res.tapIndex == 0) {
            _this.chooseWxImage('album')
          } else if (res.tapIndex == 1) {
            _this.chooseWxImage('camera')
          }
        }
      }
    })
  },

  // 选图
  chooseWxImage: function (type) {
    let _this = this;
    var picsItems;
    wx.chooseImage({
      // 相关属性设置
      count: _this.data.maxImages,
      sizeType: ['original', 'compressed'],
      sourceType: [type],
      success: function (res) {
        var imgsrc = res.tempFilePaths;
        // concat数组连接，且不会改变现有数组
        var picss = _this.data.uploadImages.concat(imgsrc);
        var imagesArr = '';
        if (picss.length >= _this.data.maxImages) {
          _this.setData({
            isMaxImagesNum: true
          });
        }
        // 判断选择的数量是否超过设定数量
        let num = picss.length <= _this.data.maxImages ? picss.length : _this.data.maxImages;
        for (var i = 0; i < num; i++) {
          imagesArr += '{"imgurl":"' + picss[i] + '"},';
        }
        imagesArr = JSON.parse('[' + imagesArr.substring(0, imagesArr.length - 1) + ']');
        _this.setData({
          uploadImages: picss,
          picsItems: imagesArr
        });
      },

    })

  },

  // 预览所选图片
  selImagePre: function (e) {
    let _this = this;
    var current = e.currentTarget.dataset.src
    wx.previewImage({
      urls: this.data.uploadImages,
      current
    })
    console.log(this.data.urls)
  },

  upload: function () {
    // if (!this.data.uploadImages.length) {
    //   wx.showToast({
    //     icon: 'none',
    //     title: '图片内容为空'
    //   });
    // } 
    
      //上传图片到云存储
      wx.showLoading({
        title: '上传中',
      })

      let promiseArr = [];
      for (let i = 0; i < this.data.uploadImages.length; i++) {
        promiseArr.push(new Promise((reslove, reject) => {
          let item = this.data.uploadImages[i];
          let suffix = /\.\w+$/.exec(item)[0];//正则表达式返回文件的扩展名
          let cloudPath = "Acitivity/" + app.globalData.openid + Date.now() + suffix;
          wx.cloud.uploadFile({
            cloudPath, // 上传至云端的路径
            filePath: item, // 小程序临时文件路径
            success: res => {
              this.setData({
                cloudImages: this.data.cloudImages.concat(res.fileID)
              });
              console.log(res.fileID)//输出上传后图片的返回地址
              reslove();
              wx.hideLoading();
              wx.showToast({
                title: "上传成功",
              })
            },
            fail: res => {
              wx.hideLoading();
              wx.showToast({
                title: "上传失败",
              })
            }

          })
        }));
      }
      Promise.all(promiseArr).then(res => {//等数组都做完后做then方法
        console.log("图片上传完成后再执行")
        this.data.Myhistory.Images = this.data.cloudImages
        this.data.Myhistory.AbilityType = this.data.AbilityType
        this.submit()
      })

    }
  ,
  toChange9: function () {
    wx.navigateTo({
      url: '../mark/mark'
    });
  }


})